package com.book.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.book.bean.OrderInfo;
import com.book.bean.OrderListInfo;
import com.book.bean.Users;
import com.book.dao.OrderInfoDao;
import com.book.util.DBUtil;

public class OrderInfoDaoImpl implements OrderInfoDao {

	@Override
	public boolean addOrders(OrderInfo orderInfo) throws Exception {
		Connection conn = DBUtil.getConn();
		String sql = "insert into order_info(uid,address) values(?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, orderInfo.getUsers().getUid());
		ps.setString(2, orderInfo.getUsers().getAddress());
		return ps.executeUpdate() == 1;

	}

	@Override
	public int getMazId() throws Exception {
		Connection conn = DBUtil.getConn();
		String sql = "SELECT MAX(order_id) FROM order_info";
		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			return rs.getInt(1);
		}
		return 0;
	}

	@Override
	public List<OrderInfo> getOrderByUser(int uid) throws Exception {
		Connection conn = DBUtil.getConn();
		//select o.order_id,ol.ol_id,u.uid,u.uname,u.phone,u.address,ol.olnum,ol.pay,ol.odate from order_info o,users u,orderlist_info ol where o.uid=u.uid and o.order_id=ol.order_id and u.uid=10;
		String sql = "select o.order_id,ol.ol_id,u.uid,u.uname,u.phone,u.address,ol.olnum,ol.pay,ol.odate "
				+ "from order_info o,users u,orderlist_info ol "
				+ "where o.uid=u.uid and o.order_id=ol.order_id "
				+ "and u.uid=? ";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, uid);
		ResultSet rs = ps.executeQuery();
		List<OrderInfo> oList = new ArrayList<OrderInfo>();
		while (rs.next()) {
			OrderInfo order = new OrderInfo();
			order.setOrder_id(rs.getInt(1));
			OrderListInfo orderList = new OrderListInfo();
			orderList.setOl_id(rs.getInt(2));
			Users user = new Users();
			user.setUid(rs.getInt(3));
			user.setUname(rs.getString(4));
			user.setPhone(rs.getString(5));
			user.setAddress(rs.getString(6));
			orderList.setOlnum(rs.getInt(7));
			orderList.setPay(rs.getDouble(8));
			orderList.setOdate(rs.getDate(9));
			order.setOrderListInfo(orderList);
			order.setUsers(user);
			oList.add(order);
		}
		return oList;
	}

}
